﻿using JWT.Algorithms;
using JWT.Serializers;
using JWT;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;

namespace FastIM
{
    public class Helper
    {
        public static bool IgnoreNullValue = false;
        /// <summary>
        /// object序列化
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string SerializeObject(object? value)
        {
            var jSetting = new JsonSerializerSettings { NullValueHandling = IgnoreNullValue ? NullValueHandling.Ignore : NullValueHandling.Include , ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() };
            return JsonConvert.SerializeObject(value, Formatting.Indented, jSetting);
        }

        public static string SecretKey = ".abcdefghijklmnopqrstuvwxyz@1234567890-";//这个服务端加密秘钥 属于私钥
        /// <summary>
        /// <seealso cref="https://github.com/jwt-dotnet/jwt#JwtNet-ASPNET-Core"/>
        /// <seealso cref="https://www.5axxw.com/wiki/content/pjne4b"/>
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="clientMetaData"></param>
        /// <returns></returns>
        public static string EncodeToken(string clientId, ClientMetaData clientMetaData)
        {
            var payload = new Dictionary<string, dynamic>
            {
                {"clientId", clientId},//用于存放当前登录人账户信息
                {"clientMetaData",clientMetaData}//用于存放当前登录人信息
            };
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            return encoder.Encode(payload, SecretKey);
        }
        /*
        public static (string clientId, ClientMetaData clientMetaData) Decode(string token)
        {
            try
            {
                var json = DecodeJson(token);
                (string clientId, ClientMetaData clientMetaData) info = JsonConvert.DeserializeObject<(string clientId, ClientMetaData clientMetaData)>(json);
                // return (info.clientId, JsonConvert.DeserializeObject<ClientMetaData>(info.clientMetaData));
                return info;
            }
            catch (Exception)
            {
                throw;
            }
        }*/

        public static (string clientId, ClientMetaData clientMetaData) DecodeToken(string token)
        {
            try
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                var provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
                //var json = decoder.Decode(token, SecretKey, verify: true);
                //return json;
                var payload = decoder.DecodeToObject<IDictionary<string, object>>(token, SecretKey, verify: true);
                if (!payload.ContainsKey("clientId")) return (null, null);
                var clientMetaData = payload["clientMetaData"].ToString();
                return (payload["clientId"].ToString(), JsonConvert.DeserializeObject<ClientMetaData>(clientMetaData));
                //Console.WriteLine(payload["claim2"]);

            }
            catch (Exception)
            {
                throw;
            }
        }

    }
}
